package com.example.gitclient.ui;

import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.gitclient.R;
import com.example.gitclient.adapter.FileAdapter;
import com.example.gitclient.git.GitManager;
import com.example.gitclient.model.GitFile;
import com.example.gitclient.model.Repository;
import com.example.gitclient.utils.RepositoryManager;

import org.eclipse.jgit.api.errors.GitAPIException;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 文件浏览器界面，显示仓库文件和状态
 */
public class FileExplorerActivity extends AppCompatActivity {
    private RecyclerView recyclerFiles;
    private TextView tvCurrentPath;
    private Button btnParentDirectory;

    private Repository repository;
    private GitManager gitManager;
    private RepositoryManager repositoryManager;
    private File currentDirectory;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_explorer);

        // 初始化视图
        recyclerFiles = findViewById(R.id.recyclerFiles);
        tvCurrentPath = findViewById(R.id.tvCurrentPath);
        btnParentDirectory = findViewById(R.id.btnParentDirectory);
        Button btnStageAll = findViewById(R.id.btnStageAll);
        Button btnUnstageAll = findViewById(R.id.btnUnstageAll);
        
        recyclerFiles.setLayoutManager(new LinearLayoutManager(this));

        // 获取仓库路径
        String repositoryPath = getIntent().getStringExtra("repository_path");
        if (repositoryPath == null) {
            Toast.makeText(this, R.string.repository_not_found, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化仓库管理器
        repositoryManager = new RepositoryManager(this);

        // 加载仓库
        loadRepository(repositoryPath);

        // 设置按钮点击事件
        btnParentDirectory.setOnClickListener(v -> navigateToParentDirectory());
        btnStageAll.setOnClickListener(v -> stageAllFiles());
        btnUnstageAll.setOnClickListener(v -> unstageAllFiles());
    }

    /**
     * 加载仓库
     * @param repositoryPath 仓库路径
     */
    private void loadRepository(String repositoryPath) {
        // 查找仓库
        for (Repository repo : repositoryManager.getRepositories()) {
            if (repo.getPath().equals(repositoryPath)) {
                repository = repo;
                break;
            }
        }

        if (repository == null) {
            Toast.makeText(this, R.string.repository_not_found, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 打开Git仓库
        try {
            gitManager = new GitManager(repository);
            currentDirectory = repository.getDirectory();
            updateUI();
            loadFiles();
        } catch (IOException e) {
            Toast.makeText(this, getString(R.string.failed_to_open_repository) + ": " + e.getMessage(), Toast.LENGTH_LONG).show();
            finish();
        }
    }

    /**
     * 更新UI
     */
    private void updateUI() {
        tvCurrentPath.setText(currentDirectory.getAbsolutePath().replace(repository.getDirectory().getAbsolutePath(), ""));
        btnParentDirectory.setEnabled(!currentDirectory.equals(repository.getDirectory()));
    }

    /**
     * 加载文件列表
     */
    private void loadFiles() {
        try {
            List<GitFile> files = gitManager.getStatus();
            // 重新加载文件状态
            FileAdapter fileAdapter = new FileAdapter(files, file -> {
                try {
                    if (file.isStaged()) {
                        gitManager.unstageFile(file.getPath());
                        Toast.makeText(FileExplorerActivity.this, R.string.file_unstaged, Toast.LENGTH_SHORT).show();
                    } else {
                        gitManager.stageFile(file.getPath());
                        Toast.makeText(FileExplorerActivity.this, R.string.file_staged, Toast.LENGTH_SHORT).show();
                    }
                    loadFiles(); // 重新加载文件状态
                } catch (GitAPIException e) {
                    Toast.makeText(FileExplorerActivity.this, getString(R.string.operation_failed, e.getMessage()), Toast.LENGTH_LONG).show();
                }
            });
            recyclerFiles.setAdapter(fileAdapter);
        } catch (GitAPIException e) {
            Toast.makeText(this, getString(R.string.load_file_status_failed, e.getMessage()), Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 导航到父目录
     */
    private void navigateToParentDirectory() {
        if (currentDirectory != null && !currentDirectory.equals(repository.getDirectory())) {
            currentDirectory = currentDirectory.getParentFile();
            updateUI();
            loadFiles();
        }
    }

    /**
     * 暂存所有文件
     */
    private void stageAllFiles() {
        try {
            gitManager.stageAll();
            loadFiles(); // 重新加载文件状态
            Toast.makeText(this, R.string.all_files_staged, Toast.LENGTH_SHORT).show();
        } catch (GitAPIException e) {
            Toast.makeText(this, getString(R.string.stage_all_failed, e.getMessage()), Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 取消暂存所有文件
     */
    private void unstageAllFiles() {
        try {
            gitManager.unstageAll();
            loadFiles(); // 重新加载文件状态
            Toast.makeText(this, R.string.all_files_unstaged, Toast.LENGTH_SHORT).show();
        } catch (GitAPIException e) {
            Toast.makeText(this, getString(R.string.unstage_all_failed, e.getMessage()), Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (gitManager != null) {
            gitManager.close();
        }
    }


}